package com.event.usc.background;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


public class Crawler extends Thread{
	private DatabaseHandler handler;
	private String url;
	private String baseUrl="http://web-app.usc.edu/ws/eo2/xml/32/list/";
	private DefaultHttpClient httpClient;
	private EventParser parser;
	private SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
	public static String apiUrl = "http://web-app.usc.edu/ws/eo2/xml/32/list/";
	public Crawler(String url)
	{
		this.url = url;
		this.parser = new EventParser();
	}
	public Crawler()
	{
		this(null);
	}
	
	public void run()
	{
		
		Calendar date = Calendar.getInstance();
		date.add(Calendar.DATE, 7);
		String suffix = format.format(date.getTime());
		url = baseUrl + suffix;
		process(date);
		cleanDate(date);
		while(true)
		{
			try {
				sleep(1800000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Calendar now = Calendar.getInstance();
			now.add(Calendar.DATE, 7);
			if (now.get(Calendar.DATE)!=date.get(Calendar.DATE))
			{
				date.add(Calendar.DATE, 1);
				suffix = format.format(date.getTime());
				url = baseUrl + suffix;
				process(date);
				cleanDate(date);
			}
		}
		
		
	}
	
	public void cleanDate(Calendar calendar)
	{
		calendar.set(Calendar.HOUR_OF_DAY, 1);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
	}
	public void process(Calendar calendar)
	{
		try
		{
			parser.setCalendar(calendar);
			httpClient = new DefaultHttpClient();
			HttpGet getreq = new HttpGet(url);
			HttpResponse response = httpClient.execute(getreq);
			if (response.getStatusLine().getStatusCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
				   + response.getStatusLine().getStatusCode());
			}
			List<Event> result = parser.parse(response.getEntity().getContent());
			httpClient.getConnectionManager().shutdown();
			writeTodb(result);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	private void writeTodb(List<Event> events) {
		handler = new DatabaseHandler();
		handler.insertRecordToDB(events);
		handler.closeConnection();
	}
}
